package com.mlt.back.web.servlet;
import com.mlt.back.beans.Manager;
import com.mlt.back.exceptions.NotFindException;
import com.mlt.back.exceptions.WrongValueException;
import com.mlt.back.service.ManagerService;
import com.mlt.back.service.RoleService;
import com.mlt.back.service.impl.ManagerServiceImpl;
import com.mlt.back.service.impl.RoleServiceImpl;
import com.mlt.back.utils.DBUtil;
import com.mlt.back.utils.IPUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;


@WebServlet({"/back/updateManager","/back/delByMgrId","/back/selectByMgrId","/back/selectByRole","/back/checkEmail","/back/managerLogin","/back/managerAdd","/back/exit","/back/checkLoginName","/back/checkMgrTel"})
public class ManagerServlet extends HttpServlet {
    private ManagerService managerService=new ManagerServiceImpl();
    private RoleService roleService=new RoleServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取请求路径
        String servletPath = request.getServletPath();
        //设置request编码,防止中文乱码
        request.setCharacterEncoding("UTF-8");
        //用户登录
        if ("/back/managerLogin".equals(servletPath)){
            doManagerLogin(request,response);
        }
        //添加管理员操作
        if ("/back/managerAdd".equals(servletPath)){
            doManagerAdd(request,response);
        }
        //删除管理员
        if ("/back/delByMgrId".equals(servletPath)){
            doDel(request,response);
        }
        //修改管理员信息
        if ("/back/updateManager".equals(servletPath)){
            doUpdate(request,response);
        }
        //根据管理员编号查询管理员
        if ("/back/selectByMgrId".equals(servletPath)){
            doSelectById(request,response);
        }
        //退出系统，删除session中的user对象
        if ("/back/exit".equals(servletPath)){
            doExit(request,response);
        }
        //根据角色分类查询管理员
        if ("/back/selectByRole".equals(servletPath)){
            doSelectByRole(request,response);
        }
        //检查登录名是否重复
        if ("/back/checkLoginName".equals(servletPath)){
            doCheckName(request,response);
        }
        //检查手机号是否重复
        if ("/back/checkMgrTel".equals(servletPath)){
            doCheckTel(request,response);
        }
        //检查邮箱是否重复
        if ("/back/checkEmail".equals(servletPath)){
            doCheckEmail(request,response);
        }
    }

    private void doUpdate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String mgr_id = request.getParameter("mgr_id");
        String login_name=request.getParameter("login_name");
        String login_pwd = request.getParameter("login_pwd");
        /*String mgr_name = request.getParameter("mgr_name");*/
        String gender = request.getParameter("mgr_gender");
        String mgr_tel = request.getParameter("mgr_tel");
        String mgr_email = request.getParameter("mgr_email");
        String role_id = request.getParameter("role_id");
        /*String mgr_qq = request.getParameter("mgr_qq");*/
        Date create_time=new Date(System.currentTimeMillis());
        String mgr_gender=gender.equals("1")?"男":"女";
        //封装Manager对象
        Manager manager=new Manager(mgr_id,login_name,login_pwd,null,mgr_gender,mgr_tel,mgr_email,null,create_time);
        managerService.update(manager,role_id);
        response.sendRedirect(request.getContextPath()+"/admin_manager_list.jsp");
    }

    private void doDel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String mgr_id = request.getParameter("mgr_id");
        int mgr_id1= Integer.parseInt(mgr_id);
        roleService.del(mgr_id1);
        managerService.del(mgr_id1);
    }

    private void doSelectById(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String mgr_id = request.getParameter("mgr_id");
        Manager manager=managerService.selectById(mgr_id);
        request.getSession().setAttribute("editManager",manager);
    }

    private void doSelectByRole(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String role_id = request.getParameter("role_id");
        int page =(Integer.parseInt(request.getParameter("page"))-1)*10;
        List<Manager> managerList=managerService.selectByRole(role_id,page);
        request.getSession().setAttribute("ManagerList",managerList);
        response.sendRedirect(request.getContextPath()+"/admin_manager_list.jsp");
    }

    private void doCheckEmail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name="mgr_email";
        String value = request.getParameter(name);
        String s = managerService.doCheck(name, value);
        if (s!=null){
            response.getWriter().print(s);
        }else {
            response.getWriter().print("0");
        }
    }

    private void doCheckTel(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name="mgr_tel";
        String value = request.getParameter(name);
        String s = managerService.doCheck(name, value);
        if (s!=null){
            response.getWriter().print(s);
        }else {
            response.getWriter().print("0");
        }
    }

    private void doCheckName(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name="login_name";
        String value=request.getParameter("login_name");
        String s=managerService.doCheck(name,value);
        if (s!=null){
            response.getWriter().print(s);
        }else {
            response.getWriter().print("0");
        }
    }

    private void doExit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.removeAttribute("IP");
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

    private void doManagerLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        //获取用户ip,存入session
        try {
            String ip = IPUtil.getIP(request);
            session.setAttribute("IP",ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //将basePath存入session
        String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
        session.setAttribute("basePath",basePath);

        //登录操作
        response.setContentType("text/html;charset=UTF-8");
        String login_name = request.getParameter("login_name");
        String login_pwd = request.getParameter("login_pwd");
        String remember = request.getParameter("remember");
        String code = request.getParameter("code");
        String r_code = (String) session.getAttribute("code");
        try {
            if (!code.equals(r_code)){
                response.getWriter().print("<h2>验证码错误</h2>");
            }else {
                Manager manager = managerService.doLogin(login_name, login_pwd);
                //执行到这里说明用户名密码正确
                //判断是否保存密码
                if ("yes".equals(remember)) {
                    Cookie cookie = new Cookie("login_name", login_name);
                    Cookie cookie1 = new Cookie("login_pwd", login_pwd);
                    //设置cookie寿命，3天
                    cookie.setMaxAge(60 * 60 * 24 * 3);
                    cookie1.setMaxAge(60 * 60 * 24 * 3);
                    //设置cookie访问路径，访问时带此路径就能发送cookie给服务器
                    cookie.setPath(request.getContextPath());
                    cookie1.setPath(request.getContextPath());
                    //把cookie响应给浏览器
                    response.addCookie(cookie);
                    response.addCookie(cookie1);
                }
                //跳转到登录成功后页面
                /*response.sendRedirect(request.getContextPath()+"/index.jsp");*/
                //把登录对象传入session
                session.setAttribute("user", manager);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        } catch (NotFindException e) {
            //没找到用户提示
            response.getWriter().print("<h2>没有用户</h2>");
        } catch (WrongValueException e) {
            //密码错误提示
            response.getWriter().print("<h2>密码错误</h2>");
        }
    }

    private void doManagerAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String login_name=request.getParameter("login_name");
        String login_pwd = request.getParameter("login_pwd");
        /*String mgr_name = request.getParameter("mgr_name");*/
        String gender = request.getParameter("mgr_gender");
        String mgr_tel = request.getParameter("mgr_tel");
        String mgr_email = request.getParameter("mgr_email");
        String role_id = request.getParameter("role_id");
        /*String mgr_qq = request.getParameter("mgr_qq");*/
        Date create_time=new Date(System.currentTimeMillis());
        String mgr_gender=gender.equals("1")?"男":"女";
        //封装Manager对象
        Manager manager=new Manager(null,login_name,login_pwd,null,mgr_gender,mgr_tel,mgr_email,null,create_time);
        //开启事务
        try (Connection conn= DBUtil.getConnection()){
            //关闭自动提交
            conn.setAutoCommit(false);
            //调用添加manager和role_id的方法
            int count=managerService.addManager(manager,role_id);
            //count为2时，表示两张表都操作成功
            if (count!=2){
                //添加失败
                response.sendRedirect(request.getContextPath()+"/error.jsp");
            }
            conn.commit();
            //跳转回添加按钮页面
            System.out.println("即将跳转");
            response.sendRedirect(request.getContextPath()+"/admin_manager_list.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                DBUtil.close(DBUtil.getConnection(),null,null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
